package com.czy.util.json;

import com.czy.convert.Converter;
import com.czy.enums.IEnum;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;

/**
 * json=>对象
 * @author czy
 */

public class DeserializerStr2IEnum<I extends IEnum<T>,T> extends JsonDeserializer<I> implements ContextualDeserializer, Converter<String, I> {
    private Class<I> targetClass = null;

    public DeserializerStr2IEnum() {
    }

    public DeserializerStr2IEnum(Class<I> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public I deserialize(JsonParser p, DeserializationContext ctxt) {
        try {
            return convert(p.getText());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public JsonDeserializer<I> createContextual(DeserializationContext ctxt, BeanProperty property) {
        Class<I> targetClass = (Class<I>) ctxt.getContextualType().getRawClass();
        return new DeserializerStr2IEnum(targetClass);
    }

    @Override
    public I convert(String source) {
        return IEnum.getBean(source, targetClass);
    }
}
